import "./style.css";
import { GomokuGame } from "./src/game.js";
import { NetworkManager } from "./src/networking.js";

/** 当前游戏状态，游戏数据 */
const game = new GomokuGame();
let networkManager;

function createUI() {
  const container = document.createElement("div");
  container.className = "game-container";

  // Menu
  const menu = document.createElement("div");
  menu.className = "menu";

  const createButton = document.createElement("button");
  createButton.textContent = "创建房间";
  createButton.onclick = createGame;

  const joinContainer = document.createElement("div");
  const roomInput = document.createElement("input");
  roomInput.placeholder = "请输入房间 ID";
  const joinButton = document.createElement("button");
  joinButton.textContent = "加入房间";
  joinButton.onclick = () => joinGame(roomInput.value);

  joinContainer.appendChild(roomInput);
  joinContainer.appendChild(joinButton);

  menu.appendChild(createButton);
  menu.appendChild(joinContainer);

  // Game Board
  const board = document.createElement("div");
  board.className = "board";
  board.style.display = "none";

  for (let i = 0; i < game.boardSize; i++) {
    const row = document.createElement("div");
    row.className = "row";

    for (let j = 0; j < game.boardSize; j++) {
      const cell = document.createElement("div");
      cell.className = "cell";
      cell.dataset.row = i;
      cell.dataset.col = j;
      cell.addEventListener("click", handleCellClick);
      row.appendChild(cell);
    }

    board.appendChild(row);
  }

  const status = document.createElement("div");
  status.className = "status";
  status.textContent = "等待对手加入中...";

  const roomInfo = document.createElement("div");
  roomInfo.className = "room-info";

  container.appendChild(menu);
  container.appendChild(board);
  container.appendChild(status);
  container.appendChild(roomInfo);

  return container;
}

function createGame() {
  initializeNetworking();
  networkManager.createRoom();
  showGame();
}

function joinGame(roomId) {
  if (!roomId) {
    alert("请输入房间ID");
    return;
  }
  initializeNetworking();
  networkManager.joinRoom(roomId);
  showGame();
}

function initializeNetworking() {
  networkManager = new NetworkManager(
    handleGameStart,
    handleOnlineMove,
    handlePlayerLeft
  );
}

function handleGameStart({ black }) {
  // 判断当前客户端玩家是否是黑棋，用于适配皮肤模式
  const isBlack = black === networkManager.playerId;
  game.setOnlineMode(isBlack ? "black" : "white");
  updateStatus();
  document.querySelector(
    ".room-info"
  ).textContent = `房间 ID: ${networkManager.roomId}`;
}

/** 广播下棋事件（主要针对对手棋） */
function handleOnlineMove({ row, col, player }) {
  const isOpponentMove = player !== networkManager.playerId;
  if (isOpponentMove) {
    game.makeMove(row, col);
    updateBoard();
    game.isMyTurn = true;
    updateStatus();
  }
}

function handlePlayerLeft() {
  alert("对手已离开房间");
  location.reload();
}

/** 客户端下棋事件 */
function handleCellClick(event) {
  if (!game.isMyTurn) return;
  const row = parseInt(event.target.dataset.row);
  const col = parseInt(event.target.dataset.col);
  const moveResult = game.makeMove(row, col);
  /** 无效操作拦截 */
  if (!moveResult) return;

  if (game.onlineMode) {
    networkManager.makeMove(row, col);
  }
  updateBoard();
  updateStatus();
}

/** 根据最新棋牌数组数据渲染棋子 */
function updateBoard() {
  const cells = document.querySelectorAll(".cell");
  cells.forEach((cell) => {
    const row = parseInt(cell.dataset.row);
    const col = parseInt(cell.dataset.col);
    cell.className = "cell";
    if (game.board[row][col]) {
      cell.classList.add(game.board[row][col]);
    }
  });
}

function nameMap(str) {
  return str === "black" ? "黑棋" : "白棋";
}
/** 游戏提示条文案 */
function updateStatus() {
  const status = document.querySelector(".status");
  if (game.gameOver) {
    alert(
      game.currentPlayer === game.playerColor
        ? "高超的棋艺，你赢了！"
        : "技不如人，你输了！"
    );
    status.textContent = `${nameMap(game.currentPlayer)} 获胜!`;
  } else if (game.onlineMode) {
    // 游戏刚开始时，第一步棋提示文案，只出现一次
    status.textContent = game.isMyTurn ? "你的回合" : "对手回合";
  } else {
    status.textContent = `${nameMap(game.currentPlayer)}回合`;
  }
}

function showGame() {
  document.querySelector(".menu").style.display = "none";
  document.querySelector(".board").style.display = "inline-block";
}

document.querySelector("#app").innerHTML = "";
document.querySelector("#app").appendChild(createUI());
